<template>
  <view class="content-review-container">
    <!-- 顶部导航 -->
    <view class="review-header">
      <text class="header-title">内容审核中心</text>
      <view class="header-right">
        <text class="admin-name">审核员：{{ adminName }}</text>
      </view>
    </view>

    <!-- 筛选工具栏 -->
    <view class="filter-bar">
      <uni-search-bar 
        placeholder="搜索内容/用户ID" 
        v-model="searchKey"
        @confirm="handleSearch"
        cancel-button="none"
        bg-color="#f8f9fa"
      ></uni-search-bar>
      <view class="filter-tabs">
        <view class="tab-item active">
          待审核（{{ total }}）
        </view>
      </view>
    </view>

    <!-- 内容列表 -->
    <scroll-view 
      class="content-list"
      scroll-y
      @scrolltolower="loadMore"
      :scroll-top="scrollTop"
    >
      <!-- 空状态提示 -->
      <view v-if="showList.length === 0" class="empty-state">
        <image src="/static/empty.png" class="empty-icon"></image>
        <text class="empty-text">暂无待审内容</text>
      </view>

      <!-- 内容项 -->
      <view 
        v-for="item in showList"
        :key="item._id"
        class="content-card pending"
      >
        <view class="card-header">
          <view class="user-info">
            <image class="user-avatar" :src="item.avatar || '/static/default-avatar.png'"></image>
            <view>
              <text class="user-name">{{ item.author }}</text>
              <!-- <text class="user-id">ID: {{ item._id.slice(-6) }}</text> -->
            </view>
          </view>
          <uni-tag 
            text="待审核"
            type="warning"
            size="small"
          />
        </view>

        <view class="card-content">
          <text class="content-title">{{ item.title }}</text>
          <text class="content-text">{{ item.content }}</text>
          <view v-if="item.images.length" class="image-grid">
            <image 
              v-for="(img, idx) in item.images"
              :key="idx"
              :src="img"
              class="content-image"
              mode="aspectFill"
              @tap="previewImage(img, item.images)"
            ></image>
          </view>
        </view>

        <view class="card-footer">
          <text class="submit-time">{{ item.create_time | formatTime }}</text>
          <view class="action-buttons">
            <button 
              class="btn pass"
              @tap="handleReview(item, 'pass')"
            >通过</button>
            <button 
              class="btn reject"
              @tap="handleReview(item, 'reject')"
            >拒绝</button>
          </view>
        </view>
      </view>

      <uni-load-more 
        :status="loadingStatus"
        :content-text="{
          contentdown: '上拉加载更多',
          contentrefresh: '正在加载...',
          contentnomore: '没有更多了'
        }"
      ></uni-load-more>
    </scroll-view>

    <!-- 拒绝原因弹窗 -->
    <uni-popup ref="rejectPopup" type="dialog">
      <uni-popup-dialog 
        mode="input"
        title="请输入拒绝理由"
        placeholder="请输入拒绝原因（必填）"
        @confirm="confirmReject"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      adminName: '审核员01',
      searchKey: '',
      loadingStatus: 'more',
      page: 1,
      pageSize: 10,
      total: 0,
      allData: [],
      tempRejectItem: null,
      scrollTop: 0
    }
  },

  computed: {
    showList() {
      return this.allData
        .filter(item => {
          const keyword = this.searchKey.toLowerCase()
          return (
            item.title?.toLowerCase().includes(keyword) ||
            item.content?.toLowerCase().includes(keyword) ||
            item._id?.toLowerCase().includes(keyword)
          )
        })
        .slice(0, this.page * this.pageSize)
    }
  },

  filters: {
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const pad = n => n.toString().padStart(2, '0')
      return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
    }
  },

  created() {
    this.loadReviewData()
  },

  methods: {
    async loadReviewData() {
      try {
        const res = await uniCloud.callFunction({
          name: 'get-review-topics',
          data: {
            page: this.page,
            pageSize: this.pageSize
          }
        })
        
        if(res.result.code === 200){
          // 分页数据合并
          this.allData = this.page === 1 
            ? res.result.data 
            : [...this.allData, ...res.result.data]
          
          this.total = res.result.data.length || 0
          this.loadingStatus = this.page * this.pageSize >= this.total 
            ? 'noMore' 
            : 'more'
        }
      } catch (e) {
        uni.showToast({ title: '数据加载失败', icon: 'none' })
      }
    },

    handleSearch() {
      this.page = 1
      this.scrollTop = Math.random() // 强制刷新滚动位置
      this.loadReviewData()
    },

    loadMore() {
      if (this.loadingStatus !== 'more') return
      this.page += 1
      this.loadReviewData()
    },

    async handleReview(item, type) {
      if(type === 'pass') {
        uni.showModal({
          title: '确认通过',
          content: '确定通过该内容？',
          success: async ({ confirm }) => {
            if(confirm) {
              const success = await this.reviewTopic(item._id, 'pass')
              if(success) this.removeItemFromList(item._id)
            }
          }
        })
      } else {
        this.tempRejectItem = item
        this.$refs.rejectPopup.open()
      }
    },

    async confirmReject(reason) {
      if(!reason?.trim()) {
        uni.showToast({ title: '请输入拒绝原因', icon: 'none' })
        return
      }
      
      const success = await this.reviewTopic(
        this.tempRejectItem._id, 
        'reject', 
        reason
      )
      
      if(success) {
        this.removeItemFromList(this.tempRejectItem._id)
        this.tempRejectItem = null
        this.$refs.rejectPopup.close()
      }
    },

    async reviewTopic(topicId, action, reason = '') {
      uni.showLoading({ title: '处理中...', mask: true })
      try {
        const res = await uniCloud.callFunction({
          name: 'review-topic',
          data: { topicId, action, reason }
        })

        if(res.result.code === 200) {
          uni.showToast({ title: '操作成功', icon: 'success' })
          return true
        }
        
        uni.showToast({ 
          title: `操作失败: ${res.result.message || '未知错误'}`,
          icon: 'none',
          duration: 3000
        })
        return false
      } catch (e) {
        console.error('云函数调用失败:', e)
        uni.showToast({ 
          title: '请求失败，请检查网络',
          icon: 'none'
        })
        return false
      } finally {
        uni.hideLoading()
      }
    },

    removeItemFromList(topicId) {
      const index = this.allData.findIndex(item => item._id === topicId)
      if(index > -1) {
        this.allData.splice(index, 1)
        this.total--
        
        // 数据不足时自动加载
        if(this.showList.length < this.pageSize && this.page > 1) {
          this.page--
          this.loadReviewData()
        }
      }
    },

    previewImage(current, urls) {
      uni.previewImage({
        current,
        urls,
        indicator: 'number'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/* 保持原有样式不变 */
.content-review-container {
  padding: 30rpx;
  background: #f8f9fa;
  min-height: 100vh;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: white;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #2c3e50;
  }

  .admin-name {
    font-size: 28rpx;
    color: #666;
  }
}

.filter-bar {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);

  .filter-tabs {
    display: flex;
    padding: 20rpx 0;

    .tab-item {
      flex: 1;
      text-align: center;
      padding: 25rpx 0;
      font-size: 28rpx;
      color: #666;
      position: relative;

      &.active {
        color: #3498db;
        font-weight: bold;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 60%;
          height: 4rpx;
          background: #3498db;
          border-radius: 2rpx;
        }
      }
    }
  }
}

.content-list {
  height: calc(100vh - 360rpx);
}

.content-card {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);

  &.pending {
    border-left: 8rpx solid #f39c12;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .user-info {
      display: flex;
      align-items: center;

      .user-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }

      .user-name {
        font-size: 30rpx;
        color: #34495e;
      }

      .user-id {
        display: block;
        font-size: 24rpx;
        color: #7f8c8d;
      }
    }
  }

  .card-content {
    .content-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #2c3e50;
      margin-bottom: 20rpx;
    }

    .content-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      overflow: hidden;
    }

    .image-grid {
      margin-top: 20rpx;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 15rpx;

      .content-image {
        width: 100%;
        height: 200rpx;
        border-radius: 8rpx;
      }
    }
  }

  .card-footer {
    margin-top: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .submit-time {
      font-size: 24rpx;
      color: #999;
    }

    .action-buttons {
      display: flex;
      gap: 20rpx;

      .btn {
        padding: 12rpx 35rpx;
        font-size: 26rpx;
        border-radius: 8rpx;
        line-height: 1;

        &.pass {
          background: #2ecc71;
          color: white;
        }
        &.reject {
          background: #e74c3c;
          color: white;
        }
      }
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;

  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    opacity: 0.5;
  }

  .empty-text {
    display: block;
    color: #999;
    font-size: 28rpx;
    margin-top: 20rpx;
  }
}
</style>